package com.ljkj.cordial.chat.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.ljkj.cordial.chat.R;

import java.io.File;

/**
 * 视频预览
 */
public class VideoPreviewDialog extends Dialog implements SurfaceHolder.Callback {
    private Context mContext;
    private SurfaceView surfaceview;
    private ImageView ivDelete;
    private boolean mIsPlay = false;//是否正在播放
    private MediaPlayer mediaPlayer;
    //    private long currentTime;
    private String thumb;

    public VideoPreviewDialog(@NonNull Context context) {
        super(context, com.nic.view.R.style.CommentStyle);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        setCancelable(true);
        setContentView(R.layout.dialog_video_preview);
//        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        getWindow().setWindowAnimations(com.nic.view.R.style.dialogWindowAnim);
        surfaceview = findViewById(R.id.surfaceview);
        surfaceview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        ivDelete = findViewById(R.id.iv_close_video);
        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        SurfaceHolder holder = surfaceview.getHolder();
        holder.addCallback(this);
    }

    @Override
    public void show() {
        super.show();
        /**
         * 设置宽度全屏，要设置在show的后面
         */
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.gravity = Gravity.CENTER;
        setImageViewSize(layoutParams, thumb);
        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        getWindow().setAttributes(layoutParams);
    }

    private void setImageViewSize(WindowManager.LayoutParams layoutParams, String thumbPath) {
        try {
            if (TextUtils.isEmpty(thumbPath)) {
                layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
                return;
            }
            int dph = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240f, getContext().getResources().getDisplayMetrics());

            Bitmap bmp = BitmapFactory.decodeFile(thumbPath);
            if (bmp==null) {
                layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
                return;
            }
            int x = bmp.getWidth() - bmp.getHeight();
            if (x > 0) {
                layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                layoutParams.height = dph;
            } else {
                layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
            }
            bmp.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Dialog show(String path,String thumb) {
        this.thumb = thumb;
        show();
        start(path);
        return this;
    }

    public void start(String path) {
        mIsPlay = true;
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //只有当播放器准备好了之后才能够播放，所以播放的出发只能在触发了prepare之后
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
//                currentTime = System.currentTimeMillis();
                mediaPlayer.start();
            }
        });
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
//                System.out.println("finish time->" + (System.currentTimeMillis() - currentTime));
                dismiss();
            }
        });
    }

    public void stop() {
        if (mIsPlay) {
            if (mediaPlayer != null) {
                mIsPlay = false;
                mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }
    }

    public void destroy() {
        stop();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        //将播放器和SurfaceView关联起来
        mediaPlayer.setDisplay(holder);

        //异步缓冲当前视频文件，也有一个同步接口
        mediaPlayer.prepareAsync();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        surfaceview = null;
        destroy();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        destroy();
    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        // 解决横竖屏切换的适配问题
        Display display = ((Activity) mContext).getWindowManager().getDefaultDisplay();
        WindowManager.LayoutParams params = this.getWindow().getAttributes();
        params.width = display.getWidth();
        this.getWindow().setAttributes(params);
        this.getWindow().setGravity(Gravity.BOTTOM);
    }

}
